package com.cz.mydao.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.cz.mydao.entity.StaffExcelVo;
import com.cz.mydao.service.ExcelService;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

/**
 * 功能描述: excel导出实现类
 *
 * @author: 程长
 * @date: 2025/1/22 8:56
 * @version: 1.0
 */
@Service
public class ExcelServiceImpl implements ExcelService {

    @Override
    public void export(HttpServletResponse response) {
        try {
            // 1. 设置 默认Excel 文件名称
            String fileName = "staff_info.xlsx";
            // 2. 对文件名进行 URL 编码，避免中文乱码
            String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString());
            // 如果是 IE 浏览器，使用 "filename=" 作为名称
            String contentDisposition = "attachment; filename=\"" + encodedFileName + "\"; filename*=utf-8''" + encodedFileName;

            // 3. 创建 Excel 文件流
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", contentDisposition);

            // 3. 假设的 StaffExcelVo 数据
            List<StaffExcelVo> staffList = Arrays.asList(
                    new StaffExcelVo("1", "张三", "男", "D001", "技术部", 8000.0),
                    new StaffExcelVo("2", "李四", "女", "D002", "人事部", 6500.0),
                    new StaffExcelVo("3", "王五", "男", "D003", "财务部", 7200.0)
            );

            // 4. 使用 EasyExcel 导出 Excel
            EasyExcel.write(response.getOutputStream(), StaffExcelVo.class)
                    .excelType(ExcelTypeEnum.XLSX)
                    .sheet("员工信息")
                    .doWrite(staffList);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
